package rpt.yto.flex.remote.data.dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import rpt.yto.flex.remote.data.dao.IQueryDAO;
import rpt.yto.util.beans.SuperBean;

@SuppressWarnings({ "unchecked" })
public class QueryDAO extends SqlMapClientDaoSupport implements IQueryDAO {
	
	@Override
	public List<Object> executeQuery(String sql , Class beanType) throws Exception {
		
		List<Object> beanList = new ArrayList<Object>();
		List<Map<String , Object>> resultMap = getSqlMapClientTemplate().queryForList("query" , sql);
		
		if(resultMap == null || resultMap.size() == 0) 
			return null;
		
		for(Map<String , Object> result : resultMap) {
			
			SuperBean bean = (SuperBean) Class.forName(beanType.getName()).newInstance();
			Iterator iter = result.entrySet().iterator();
			while(iter.hasNext()) {
				Entry entry = (Entry) iter.next();
				bean.setAttributeValue(String.valueOf(entry.getKey()).toLowerCase(), entry.getValue());
			}
			
			beanList.add(bean);
			
		}
		
		if(beanList.size() == 0)
			return null;
		
		
		
		return beanList;
	}
	
}
